from sklearn import datasets
import pdb
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

df = pd.DataFrame()

def logisticRegression(x:np.ndarray, y:np.ndarray, num_iter=5000, alpha=0.01):
    w, b = np.zeros(4), 0
    m = w.shape[0]

    for _ in range(num_iter):
        z = x.dot(w) + b
        y_hat = 1 / (1 + np.e**(-z))
        error = np.array(y_hat - y)
        der_w = 1/m * np.sum(x.T.dot(error))
        der_b = 1/m * np.sum(error)
        w = w - (alpha * der_w)
        b = b - (alpha * der_b)

    return w, b

# def optimizer_logistic(X:pd.DataFrame, w:np.ndarray, b:float, num_iter=5000, alpha=0.01):
#     return w, b

def predict(x:pd.DataFrame, w:np.ndarray, b:float):
    z = x.dot(w) + b
    tmp = 1 / (1 + np.e**(-z))
    y_hat = list()
    for i in tmp:
        if i < 0.5:
            y_hat.append(0)
        else:
            y_hat.append(1)
    y_hat = np.array(y_hat)
    return y_hat

def error_variance(y_hat:np.ndarray, y_test:np.ndarray):
    m = y_hat.shape[0]
    variance = 1/m * np.sum((y_hat - y_test)**2)
    return variance


if '__main__' == __name__:
    iris = datasets.load_iris()
    df = pd.DataFrame(data=iris.data,
                    columns=iris.feature_names) #读取数据
    save = ~(iris.target == 2) #保存类别不为2的花
    X = df[save] #去除维吉尼亚鸢尾花,只留下两类花对应0,1
    y = iris.target[save]
    x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    w, b = logisticRegression(x_train, y_train)
    y_hat = predict(x_test, w, b)
    variance = error_variance(y_hat, y_test)
    print(y_hat)
    print(y_test)
